package internal

import (
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"mycms/global"
	"os"
	"time"
)

var Gorm = new(_gorm)

type _gorm struct{}

// Config gorm 自定义配置
// 更多配置参考文档：(https://gorm.io/zh_CN/docs/gorm_config.html)
func (g *_gorm) Config() *gorm.Config {
	config := &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true,	//	迁移时禁止自动创建外键约束
		NamingStrategy: schema.NamingStrategy{
			TablePrefix: global.CONFIG.Mysql.TablePrefix,	//	表前缀
			SingularTable: true,	//	使用单数表名，启用该选项后，`User` 表将是`user`
		},
	}

	//	自定义Logger
	_default := logger.New(NewWriter(log.New(os.Stdout, "\r\n", log.LstdFlags)), logger.Config{
		SlowThreshold: 200 * time.Millisecond,	// 慢 SQL 阈值
		LogLevel:      logger.Warn,				// 日志级别
		Colorful:      true,					// 启用彩色打印
		IgnoreRecordNotFoundError: true,  		// 忽略ErrRecordNotFound（记录未找到）错误
	})
	switch global.CONFIG.Mysql.LogMode {
	case "silent", "Silent":
		config.Logger = _default.LogMode(logger.Silent)
	case "error", "Error":
		config.Logger = _default.LogMode(logger.Error)
	case "warn", "Warn":
		config.Logger = _default.LogMode(logger.Warn)
	case "info", "Info":
		config.Logger = _default.LogMode(logger.Info)
	default:
		config.Logger = _default.LogMode(logger.Info)
	}
	return config
}
